;(function () {
    importCss();
    var _global;
    var numberKey = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0], numberKeyCol = 4;
    var lowercaseKey = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'],
        lowercaseKeyCol = 9;
    var capitalKey = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
        capitalKeyCol = 9;
    var symbolKey = ['!', '\"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~'],
        symbolKeyCol = 11;

    var self;
    if (!('getElementsByClassName' in HTMLElement)) {
        HTMLElement.prototype.getElementsByClassName = function (n, tar) {
            var el = [],
                _el = (!!tar ? tar : this).getElementsByTagName('*');
            for (var i = 0; i < _el.length; i++) {
                if (!!_el[i].className && (typeof _el[i].className == 'string') && _el[i].className.match(new RegExp('(\\s|^)' + n + '(\\s|$)'))) {
                    el[el.length] = _el[i];
                }
            }
            return el;
        };
        ((typeof HTMLDocument !== 'undefined') ? HTMLDocument : Document).prototype.getElementsByClassName = HTMLElement.prototype.getElementsByClassName;
    }

    var html =
        '<div class="tips">提示：上、下、左、右移动到相应按键，点击遥控器【确定】按钮后，输入相应字符，点击【收起】或【在顶部↑】则收起键盘</div>' +
        '<div id="keyboardSwitch">' +
        '<div class="switch-item" id="switchHandle1">' +
        '<div class="switch-item-wrap">123</div>' +
        '</div>' +
        '<div class="switch-item"  id="switchHandle2">' +
        '<div class="switch-item-wrap"><span>ABC</span>/<span>abc</span></div>' +
        '</div>' +
        '<div class="switch-item"  id="switchHandle3">' +
        '<div class="switch-item-wrap">符号</div>' +
        '</div>' +
        '<div class="switch-item" id="switchHandle4">' +
        '<div class="switch-item-wrap">删除</div>' +
        '</div>' +
        '<div class="switch-item" id="switchHandle5">' +
        '<div class="switch-item-wrap">收起</div>' +
        '</div>' +
        '</div>' +
        '<div id="keyboardKey">' +
        '<!--数字-->' +
        '<div id="numberKey" class="keyboard-item">' +
        '</div>' +
        '<!--小写字母-->' +
        '<div id="lowercaseKey" class="keyboard-item">' +
        '</div>' +
        '<!--大写字母-->' +
        '<div id="capitalKey" class="keyboard-item">' +
        '</div>' +
        '<!--符号字母-->' +
        '<div id="symbolKey" class="keyboard-item">' +
        '</div>' +
        '</div>';

    var Keyboard = function () {
        self = this;
        var keyboardContainer = document.createElement('div');
        keyboardContainer.id = 'keyboardContainer';
        keyboardContainer.innerHTML = html;
        document.body.appendChild(keyboardContainer);
        this.container = document.getElementById('keyboardContainer');
        keyopt.options.focusElm = 'switchHandle1';
        document.getElementById(keyopt.options.focusElm).className = 'switch-item active';
        this.listeners = []; //自定义事件，用于监听插件的用户交互
        this.caseStatus = false;//保存大小写键盘状态 真为小写，假为大写
        this.handlers = {};
        this.result = '';
        this._init();
    };

    Keyboard.prototype = {
        //删除字符
        del: function () {
            this.result = this.result.substr(0, this.result.length - 1);
            this.emit({type: 'input'})
        },
        switch: function (id) {
            var Nodes = document.getElementById('keyboardKey').getElementsByClassName('keyboard-item');
            for (var i = 0; i < Nodes.length; i++) {
                Nodes[i].style.display = 'none';
            }
            document.getElementById(id).style.display = 'block';

            for (var i = 1; i <= 5; i++) {
                _global['switchHandle' + i + '_json'].go_bottom = id + '1';
            }
            for (var i = 1; i <= eval(id + 'Col'); i++) {
                _global[id + i + '_json'].go_top = keyopt.options.focusElm;
            }

            this.emit({type: 'switch'})
        },
        //清空
        clear: function () {
            this.result = '';
            this.emit({type: 'clear'})
        },
        close: function () {
            this.container.style.display = 'none';
            this.emit({type: 'close'})
        },
        open: function (result) {
            this.container.style.display = 'block';
            this.result = result;
            this.emit({type: 'open'})
        },
        input: function (char) {
            this.result += char;
            this.emit({type: 'input'})
        },
        on: function (type, handler) {
            // type: show, shown, hide, hidden, close, confirm
            if (typeof this.handlers[type] === 'undefined') {
                this.handlers[type] = [];
            }
            this.listeners.push(type);
            this.handlers[type].push(handler);
            return this;
        },
        off: function (type, handler) {
            if (this.handlers[type] instanceof Array) {
                var handlers = this.handlers[type];
                for (var i = 0, len = handlers.length; i < len; i++) {
                    if (handlers[i] === handler) {
                        break;
                    }
                }
                this.listeners.splice(i, 1);
                handlers.splice(i, 1);
                return this;
            }
        },
        emit: function (event) {
            if (!event.target) {
                event.target = this;
            }
            if (this.handlers[event.type] instanceof Array) {
                var handlers = this.handlers[event.type];
                for (var i = 0, len = handlers.length; i < len; i++) {
                    handlers[i](event);
                    return true;
                }
            }
            return false;
        },
        _init: function () {
            this._initSwitchHandle();
            this._initNumberKey();
            this._initCapitalKey();
            this._initLowercaseKey();
            this._initSymbolKey();
            self.switch('numberKey');
        },
        _initSwitchHandle: function () {
            var switchHandleNodes = document.getElementsByClassName('switch-item');
            for (var i = 0; i < switchHandleNodes.length; i++) {
                _global[switchHandleNodes[i].id + '_json'] = {};
                _global[switchHandleNodes[i].id + '_json'].go_left = switchHandleNodes[i - 1] ? switchHandleNodes[i - 1].id : '';
                _global[switchHandleNodes[i].id + '_json'].go_top = '';
                _global[switchHandleNodes[i].id + '_json'].go_right = switchHandleNodes[i + 1] ? switchHandleNodes[i + 1].id : '';
                _global[switchHandleNodes[i].id + '_json'].go_bottom = '';

                _global[switchHandleNodes[i].id + '_onfocus'] = function (code, id) {
                    document.getElementById(id).className = 'switch-item active'
                };
                _global[switchHandleNodes[i].id + '_onblur'] = function (code, id) {
                    document.getElementById(id).className = 'switch-item';
                    if(code==='go_top'){
                        self.close()
                    }
                };
            }
            _global['switchHandle1_onsubmit'] = function (code, id) {
                //    切换到数字
                self.switch('numberKey');
            };
            _global['switchHandle2_onsubmit'] = function (code, id) {
                if (this.caseStatus) {
                    self.switch('lowercaseKey');
                    this.caseStatus = !this.caseStatus;
                } else {
                    self.switch('capitalKey');
                    this.caseStatus = !this.caseStatus;
                }
            };
            _global['switchHandle3_onsubmit'] = function (code, id) {
                self.switch('symbolKey');
            };
            _global['switchHandle4_onsubmit'] = function (code, id) {
                self.del()
            };
            _global['switchHandle5_onsubmit'] = function (code, id) {
                self.close()
            };
        },
        _initNumberKey: function () {
            var html = '';
            for (var i = 0; i < numberKey.length; i++) {
                html += '<div id="' + 'numberKey' + (i + 1) + '" class="key-item">' +
                    '<div class="key-item-wrap">' + numberKey[i] + '</div>' +
                    '</div>'
            }
            document.getElementById('numberKey').innerHTML = html;
            this._initFocus('numberKey', numberKeyCol)

        },


//初始化小写字母键盘
        _initLowercaseKey: function () {
            var html = '';
            for (var i = 0; i < lowercaseKey.length; i++) {
                html += '<div id="' + 'lowercaseKey' + (i + 1) + '" class="key-item">' +
                    '<div class="key-item-wrap">' + lowercaseKey[i] + '</div>' +
                    '</div>'
            }
            document.getElementById('lowercaseKey').innerHTML = html;

            this._initFocus('lowercaseKey', lowercaseKeyCol)
        },

//初始化大写字母键盘
        _initCapitalKey: function () {
            var html = '';
            for (var i = 0; i < capitalKey.length; i++) {
                html += '<div id="' + 'capitalKey' + (i + 1) + '" class="key-item">' +
                    '<div class="key-item-wrap">' + capitalKey[i] + '</div>' +
                    '</div>'
            }
            document.getElementById('capitalKey').innerHTML = html;
            this._initFocus('capitalKey', capitalKeyCol)
        },

//初始化符号键盘
        _initSymbolKey: function () {
            var html = '';
            for (var i = 0; i < symbolKey.length; i++) {
                html += '<div id="' + 'symbolKey' + (i + 1) + '" class="key-item">' +
                    '<div class="key-item-wrap">' + symbolKey[i] + '</div>' +
                    '</div>'
            }
            document.getElementById('symbolKey').innerHTML = html;
            this._initFocus('symbolKey', symbolKeyCol)
        },

        _initFocus: function (id, col) {
            var Nodes = document.getElementById(id).getElementsByClassName('key-item');
            for (var i = 0; i < Nodes.length; i++) {
                _global[Nodes[i].id + '_json'] = {};
                _global[Nodes[i].id + '_json'].go_left = Nodes[i - 1] ? Nodes[i - 1].id : '';
                _global[Nodes[i].id + '_json'].go_top = Nodes[i - col] ? Nodes[i - col].id : '';
                _global[Nodes[i].id + '_json'].go_right = Nodes[i + 1] ? Nodes[i + 1].id : '';
                _global[Nodes[i].id + '_json'].go_bottom = Nodes[i + col] ? Nodes[i + col].id : '';

                _global[Nodes[i].id + '_onfocus'] = function (code, id) {
                    document.getElementById(id).className = 'key-item active'
                };
                _global[Nodes[i].id + '_onblur'] = function (code, id) {
                    document.getElementById(id).className = 'key-item'
                };
                _global[Nodes[i].id + '_onsubmit'] = function (code, id) {
                    self.input(document.getElementById(id).getElementsByClassName('key-item-wrap')[0].innerHTML);
                };
            }
        }

    };


    function importCss() {
        var head = document.getElementsByTagName("head");
        var css = document.createElement("link");
        css.href = '../css/plug-in/keyboard.css';
        css.rel = "stylesheet";
        css.type = "text/css";
        head[0].appendChild(css);
    }


    function extend(target, options, deep) {
        for (var key in options) {
            if (options.hasOwnProperty(key)) {
                var copy = options[key];
                if (deep && copy instanceof Array) {
                    target[key] = extend(target[key], copy, deep);
                } else if (deep && copy instanceof Object) {
                    target[key] = extend(target[key], copy, deep);
                } else {
                    target[key] = options[key];
                }
            }
        }
        return target;
    }

    _global = (function () {
        return this || (0, eval)('this');
    }());
    if (typeof module !== "undefined" && module.exports) {
        module.exports = Keyboard;
    } else if (typeof define === "function" && define.amd) {
        define(function () {
            return Keyboard;
        });
    } else {
        !('Keyboard' in _global) && (_global.Keyboard = Keyboard);
    }
})
();
